在 DevOps 的流程裡,是透過 CI/CD Pipeline 來自動化測試與部署,但隨著專案和服務越來越多,每個 Pipeline 的狀態如果要一個一個打開頁面去看,其實是非常耗時的
因此若把 Pipeline 的狀態整合到 BOT,只要在聊天視窗裡下個指令,就能直接查到所有 Pipeline 是否正常,甚至可以即時收到通知,這樣不僅能節省時間,也能更快掌握系統狀況
一樣來撰寫這個功能的程式碼
def get_workflow_status(workflow_file=None):
"""獲取 GitHub Actions workflow 狀態"""
try:
if not GH_TOKEN:
return "❌ GitHub Token 未設定,請檢查 .env 檔案"
headers = {
'Authorization': f'token {GH_TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
# 構建 API URL
if workflow_file:
# 先獲取 workflow ID
workflow_id = get_workflow_id_by_name(workflow_file)
if workflow_id:
url = f'https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/actions/workflows/{workflow_id}/runs'
else:
# 直接使用檔案名稱嘗試
url = f'https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/actions/workflows/{workflow_file}/runs'
else:
# 獲取所有 workflow 的運行記錄
url = f'https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/actions/runs'
params = {'per_page': 5}
print(f"🌐 請求 GitHub Actions API: {url}")
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
if not data.get('workflow_runs'):
return "📭 尚未有任何 workflow 運行記錄"
return format_workflow_runs(data['workflow_runs'], workflow_file)
except requests.exceptions.HTTPError as e:
error_msg = f"❌ GitHub API 錯誤: {e.response.status_code}"
if e.response.status_code == 404:
error_msg += " - 找不到倉庫或 workflow"
error_msg += f"\n💡 請使用 `!workflow_list` 查看正確的 workflow 檔案名稱"
elif e.response.status_code == 403:
error_msg += " - 權限不足,請檢查 token 權限"
return error_msg
except Exception as e:
return f"❌ 獲取 workflow 狀態時出錯: {str(e)}"
@bot.command()
async def pipeline_status(ctx, workflow_file=None):
"""查詢 GitHub Actions Pipeline 狀態"""
print(f"📊 收到 pipeline_status 指令來自 {ctx.author}")
wait_msg = await ctx.send("🔄 正在查詢 GitHub Actions 狀態...")
if workflow_file and workflow_file.lower() == 'list':
workflow_list = get_workflow_list()
await wait_msg.edit(content=workflow_list)
else:
status_message = get_workflow_status(workflow_file)
await wait_msg.edit(content=status_message)
接著回到discord測試